#include"pSystem.h"

using namespace psys;

const DWORD Particle::FVF = D3DFVF_XYZ | D3DFVF_DIFFUSE;

PSystem::PSystem()
{
	_device = 0;
	_vb = 0;
	_tex = 0;
}

PSystem::~PSystem()
{
	d3d::Release<IDirect3DVertexBuffer9*>(_vb);
	d3d::Release<IDirect3DTexture9*>(_tex);
}

bool PSystem::init(IDirect3DDevice9* device, wchar_t* texFileName)
{
	_device = device;			//	save a ptr to the device

	HRESULT hr = 0;

	hr = device->CreateVertexBuffer(_vbSize * sizeof(Particle),
									D3DUSAGE_DYNAMIC | D3DUSAGE_POINTS | D3DUSAGE_WRITEONLY,
									Particle::FVF,
									D3DPOOL_DEFAULT,
									&_vb,
									0);
	if(FAILED(hr))
	{
		MessageBox(0,L"CreateVertexBuffer() - FAILED",L"PSystem",MB_OK);
		return false;
	}

	hr = D3DXCreateTextureFromFile(device,LPCWSTR(texFileName),&_tex);
	if(FAILED(hr))
	{
		MessageBox(0,L"D3DXCreateTextureFromFile() - FAILED",L"PSystem",MB_OK);
		return false;
	}
	return true;
}

void PSystem::reset()
{
	std::list<Attribute>::iterator i;
	for(i = _particles.begin(); i!= _particles.end();i++)
	{
		resetParticle(&(*i));
	}
}

void PSystem::addParticle()
{
	Attribute attribute;
	resetParticle(&attribute);
	_particles.push_back(attribute);
}

void PSystem::preRender()
{
	
}

void PSystem::postRender()
{

}

void PSystem::render()
{
	
}

bool PSystem::isEmpty()
{
	return _particles.empty();
}


bool PSystem::isDead()
{
	std::list<Attribute>::iterator i;
	for(i = _particles.begin(); i != _particles.end(); i++)
	{
		// is there at least one living particle?  If yes,
		// the system is not dead.
		if( i->_isAlive )
			return false;
	}
	// no living particles found, the system must be dead.
	return true;
}


void PSystem::removeDeadParticles()
{
	std::list<Attribute>::iterator i;

	i = _particles.begin();

	while( i != _particles.end() )
	{
		if( i->_isAlive == false )
		{
			// erase returns the next iterator, so no need to
		    // incrememnt to the next one ourselves.
			i = _particles.erase(i); 
		}
		else
		{
			i++; // next in list
		}
	}
}
